package ird.demo.tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

public class FileHelper extends FileUtils {
	public static final String PROPERTY_DELIMITER = "=";
	public static final String FILE_NAME_DELIMITER = "/";
	
	public static void copyFile(String srcFileStr, String destFileStr)
			throws Exception {
		copyFile(new File(srcFileStr), new File(destFileStr));
	}

	public static void copyDirectory(String srcDirStr, String destDirStr)
			throws Exception {
		copyDirectory(new File(srcDirStr), new File(destDirStr));
	}

	public static String getFileContents(String fileName) throws Exception {
		return getFileContents(fileName, Charset.defaultCharset().name());
	}
	
	public static String getFileContents(String fileName, String charSet) throws Exception {
		FileInputStream fin = new FileInputStream(fileName);
		FileChannel fch = fin.getChannel();

		// map the contents of the file into ByteBuffer
		ByteBuffer byteBuff = fch.map(FileChannel.MapMode.READ_ONLY, 0,	fch.size());

		// convert ByteBuffer to CharBuffer
		CharBuffer chBuff = Charset.forName(charSet).decode(byteBuff);
		fin.close();
		return chBuff.toString();
	}
	
	public static boolean isBlankStr(String str){
		if(str == null || "".equals(str.trim())){
			return true;
		}
		return false;
	}
	
	public static List<String> getListFileContents(String fileName) throws Exception {
		List<String> fileContents = new ArrayList<String>();
		BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));
	    String line;
	    while((line = reader.readLine())!= null)  {
	    	fileContents.add(line);
	    }
	    reader.close();
		return fileContents;
	}
	
	public static InputStream getResourceInputStream(String fileName) throws Exception{
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(FileHelper.class.getClassLoader());
		return resolver.getResource(fileName).getInputStream();
	}

	public static void main(String[] args) {
		try {
			System.out.println(getFileContents("c:/tmp/tmp.txt"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
